package com.jtjrenren.android.taxi.passenger.manger;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiAmount;
import com.jtjrenren.android.taxi.passenger.bean.event.UserRefreshEvent;
import com.jtjrenren.android.taxi.passenger.manger.api.ApiWorks;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseActivity;
import com.jtjrenren.android.taxi.passenger.bean.User;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiConfig;
import com.jtjrenren.android.taxi.passenger.bean.api.Token;
import com.jtjrenren.android.taxi.passenger.bean.event.RLoginEvent;
import com.jtjrenren.android.taxi.passenger.core.main.HomeActivity;
import com.jtjrenren.android.taxi.passenger.manger.api.PushWorks;
import com.jtjrenren.android.taxi.passenger.manger.push.PushEngine;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;
import com.library.cache.ACache;

import org.greenrobot.eventbus.EventBus;

import com.library.utils.AppUtils;
import com.library.utils.LogUtil;
import com.library.utils.SpUtils;
import com.library.utils.StringUtils;

/**
 * Created by Administrator on 2016/9/6.
 */

public class AppManger {
    private static AppManger instance;
    public int serial_no = 0; //流水号
    public BaseActivity currentActivity;

    private Context context;

    public User user;
    public BDLocation currentLocation;
    private LocationManger locationManger;
    public String gtCID;
    public String token;

    private AppManger() {
    }

    public static AppManger getInstance() {
        if (instance == null)
            instance = new AppManger();
        return instance;
    }

    public void init(Context context) {
        this.context = context;
        startLocation();
    }

    public void showMainPage() {
        if (currentActivity == null || currentActivity instanceof HomeActivity)
            return;
        currentActivity.startActivity(new Intent(currentActivity, HomeActivity.class));
    }

    //登录成功
    public void loginSuccess(User user) {
        LogUtil.log("user", "login success:" + user.toString());
        this.user = user;

        SpUtils.setParam(context, "userid", user.getWorkNo());
        SpUtils.setParam(context, "user_phone", user.getPhone());
        SpUtils.setParam(context, "lauchcount", 1);

        getToken(false);

        refreshUserDetails(user.getWorkNo());
    }

    //登出
    public void loginOut() {
        SpUtils.setParam(context, "userid", "");
        SpUtils.setParam(context, "user_phone", "");
        ACache.get(context).remove(user.getWorkNo());
        this.user = null;
        this.token = null;
    }

    //设置个推ID
    public void setGtCID(String gtCID) {
        LogUtil.log("token", "setGtCID()==>" + gtCID);
        if (!StringUtils.isEmpty(this.gtCID) && gtCID.equals(this.gtCID))
            return;
        this.gtCID = gtCID;
        if (!StringUtils.isEmpty(this.token))
            bindGtID(gtCID);
    }

    //绑定个推ID
    public void bindGtID(String id) {
        LogUtil.log("token", "bindGtID()");
        PushWorks.bindGtID(id, new ApiWorks.ResponseListener<ApiCommonT>() {
            @Override
            public void onResponse(ApiCommonT apiCommonT) {
                if (apiCommonT != null && ModuleUtils.handCommon(apiCommonT.getCode())) {
                    LogUtil.log("token", "联网绑定gt 成功");
                }
            }
        });
    }

    public void setToken(String token) {
        LogUtil.log("token", "setToken()===> token:" + token);
        this.token = token;
        ACache.get(context).put(user.getWorkNo() + "_token", token, 5 * ACache.TIME_DAY);

        if (!StringUtils.isEmpty(gtCID)) {
            bindGtID(gtCID);
        } else {
            LogUtil.log("token", "setToken  gtid is null");
        }
    }

    //isRefresh 是否必须刷新
    public void getToken(boolean isRefresh) {
        LogUtil.log("token", "getToken() isRefresh:" + isRefresh);
        if (user == null) {
            LogUtil.log("token", "getToken user is null");
            return;
        }

        if (!isRefresh) {
            ACache aCache = ACache.get(context);
            String asString = aCache.getAsString(user.getWorkNo() + "_token");
            if (!StringUtils.isEmpty(asString)) {
                setToken(asString);
                return;
            }
        }

        PushWorks.getToken(user.getPhone(), getString(R.string.appbz),
                AppUtils.getVersionName(context), new ApiWorks.ResponseListener<Token>() {
                    @Override
                    public void onResponse(Token token) {
                        if (token != null)
                            setToken(token.getToken());
                        else {
                            LogUtil.log("token", "登录异常，请重新登录 EventBus Send");
                            loginOut();
                            Toast.makeText(context, "登录异常，请重新登录", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new RLoginEvent("登录异常，请重新登录"));
                        }
                    }
                });
    }

    //获取上次登录的用户信息
    public User getRemberUser() {
        User u = null;
        String userid = (String) SpUtils.getParam(context, "userid", "");
        LogUtil.log("user", "rember user:" + userid);
        if (!StringUtils.isEmpty(userid)) {
            u = new User();
            u.setWorkNo(userid);
            u.setPhone((String) SpUtils.getParam(context, "user_phone", ""));
        }
        return u;
    }

    public boolean isLogin() {
        return user != null;
    }

    //是否登陆过
    public boolean isLauched() {
        int count = (int) SpUtils.getParam(context, "lauchcount", 0);
        if (count < 1)
            return false;
        return true;
    }

    //刷新用户缓存
    public void refreshUser(User user) {
        this.user = user;
        EventBus.getDefault().post(new UserRefreshEvent());
    }

    //刷新用户的详细信息
    public void refreshUserDetails(String userID) {
        ApiWorks.getUserDetails(userID, new ApiWorks.ResponseListener<User>() {
            @Override
            public void onResponse(User user) {
                if (user != null)
                    refreshUser(user);
            }
        });
    }

    /**
     * 向调度发送消息
     * @param msg
     */
    public void sendMsgToControl(String msg) {
        if (user == null)
            return;
        PushWorks.pushMsg(msg, null);
    }

    /**
     * 接收到推送消息
     * @param msg
     */
    public void receivePushMsg(String msg){
        Log.d("push", "接收到透传消息: " + msg);
        if (!StringUtils.isEmpty(msg))
            PushEngine.handMsg(msg);
    }

    public String getString(int id) {
        return context.getString(id);
    }

    public Context getContext() {
        return context;
    }

    private void startLocation() {
        if (locationManger == null) {
            locationManger = new LocationManger();
            locationManger.init(context);
        }
        locationManger.start();
    }

    private void stopLocation() {
        if (locationManger != null)
            locationManger.stop();
    }

    public void requestLoc() {
        if (locationManger != null)
            locationManger.request();
    }

    public void refreshConfig() {
        ApiWorks.checkAppConfig(new ApiWorks.ResponseListener<ApiConfig>() {
            @Override
            public void onResponse(ApiConfig config) {
                if (config != null) {
                    if (config != null && config.getData() != null && config.getData().size() > 0) {
                        ApiConfig.DataBean dataBean = config.getData().get(0);

                        SpUtils.setParam(context, "showyyc", dataBean.isOpt());
                    }
                }
            }
        });
    }

    /**
     * 刷新钱包余额
     */
    public void refreshQBYE(String money) {
        if (!StringUtils.isEmpty(money)) {
            user.setRMBMoney(money);
            return;
        }
        ApiWorks.getUserAmountDetails(user.getWorkNo(), new ApiWorks.ResponseListener<ApiAmount>() {
            @Override
            public void onResponse(ApiAmount apiAmount) {
                if (apiAmount != null && apiAmount.getDataList() != null && apiAmount.getDataList().size() > 0) {
                    ApiAmount.DataListEntity amount = apiAmount.getDataList().get(0);
                    user.setRMBMoney(amount.getMoney());
                }
            }
        });
    }

}
